﻿using UnityEngine;
using System.Collections;
using System.Net;
using SGLib.Net;
using System.Collections.Generic;
using System;
using PBMessage;

public class GameNet : MonoBehaviour
{
    IPEndPoint mServerIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6542);
    NetClient mNetClient;
    public NetClient NetClient { get { return mNetClient; }}
    GameCodec mGameCodec = new GameCodec();
    Action mConnectEvent;

    Dictionary<PBMesasgeID, System.Action<PBPackage>> registerHandlers = new Dictionary<PBMesasgeID, Action<PBPackage>>();
    public void Connect(System.Action fn)
    { 
        mConnectEvent = fn;
        mNetClient = new NetClient(mGameCodec, packageHandlerFunc);
        mNetClient.ConnectAsync(mServerIP);
        mNetClient.Connected += onConnected;
        mNetClient.NetErrorEvent += onNetErrorEvent;
    }

    private void onNetErrorEvent(string obj)
    {
        Debug.LogError(obj);
    }

    bool connectedTrigger  = false;
    private void onConnected(object sender, System.EventArgs e)
    {
        connectedTrigger = true;
    }
    public void SetHandler(PBMesasgeID id, System.Action<PBPackage> fn)
    {
        registerHandlers[(PBMesasgeID)id] = fn;
    }

    CS_LobbyTick csTick  =new PBMessage.CS_LobbyTick();
    void packageHandlerFunc(IPackage pkg)
    {
        PBPackage package = (PBPackage)pkg;
        if (package.MessageID == (int)PBMesasgeID.SC_LobbyTick)
        {
            csTick.Time = System.DateTime.Now.Ticks;
            LobbyModel.Instance.LobbyNumber = (int)((SC_LobbyTick)package.Data).PlayerNumber;
            mNetClient.Send((int)PBMesasgeID.CS_LobbyTick, csTick);
        }
        else
        {
            Debug.Log(package.Data);
        }
       
        if (registerHandlers.ContainsKey((PBMesasgeID)package.MessageID))
        {
            var fn = registerHandlers[(PBMesasgeID)package.MessageID];
            fn(package);
        }
       
    }
    void Update()
    {
        if (mNetClient != null)
        {
            if (connectedTrigger && mConnectEvent != null)
            {
                connectedTrigger = false;
                mConnectEvent();
            }
            mNetClient.Update();
        }
    }
    public void OnApplicationQuit()
    {
        if (mNetClient != null)
        {
            mNetClient.Close();
        }
    }
}
